// 用户服务 - 管理用户数据的存储和检索
import { getItem, setItem } from '../utils/storage.js'
import { hashPassword, verifyPassword, convertToHashedPassword } from '../utils/cryptoUtils.js'

// 成就类型常量
export const ACHIEVEMENT_TYPES = {
  FIRST_GAME: '首次游戏',
  TEN_GAMES: '游戏达人',
  BEST_REACTION: '反应大师',
  HIGH_SCORE: '得分王',
  VIP_MEMBER: 'VIP会员'
}

// 存储键常量
const STORAGE_KEYS = {
  USERS: 'users',
  USER_STATS: (username) => `userStats_${username}`,
  USER_ACHIEVEMENTS: (username) => `userAchievements_${username}`,
  RECENT_GAMES: (username) => `recentGames_${username}`
}

// 获取所有用户
export const getAllUsers = () => {
  try {
    let users = getItem(STORAGE_KEYS.USERS)
    
    if (!users) {
      // 默认用户数据，使用哈希密码
      users = [
        { 
          username: 'admin', 
          password: hashPassword('admin123'), 
          isVIP: true, 
          vipExpiry: getVipExpiryDate(30), 
          email: 'admin@example.com', 
          bio: '系统管理员' 
        },
        { 
          username: 'user1', 
          password: hashPassword('user123'), 
          email: 'user1@example.com' 
        }
      ]
      setItem(STORAGE_KEYS.USERS, users)
    } else {
      // 检查并转换旧的明文密码
      const hasUsersWithPlaintextPasswords = users.some(user => 
        user.password && !user.password.startsWith('hash_')
      )
      
      if (hasUsersWithPlaintextPasswords) {
        users = users.map(convertToHashedPassword)
        setItem(STORAGE_KEYS.USERS, users)
      }
    }
    
    return users
  } catch (error) {
    console.error('获取用户数据失败:', error)
    // 返回默认用户（使用哈希密码）
    return [
      { 
        username: 'admin', 
        password: hashPassword('admin123'), 
        isVIP: true, 
        vipExpiry: getVipExpiryDate(30), 
        email: 'admin@example.com', 
        bio: '系统管理员' 
      },
      { 
        username: 'user1', 
        password: hashPassword('user123'), 
        email: 'user1@example.com' 
      }
    ]
  }
}

// 获取VIP过期日期
export const getVipExpiryDate = (days) => {
  const date = new Date()
  date.setDate(date.getDate() + days)
  return date.toISOString()
}

// 保存用户列表
export const saveUsers = (users) => {
  try {
    // 确保所有密码都是哈希格式
    const usersWithHashedPasswords = users.map(convertToHashedPassword)
    return setItem(STORAGE_KEYS.USERS, usersWithHashedPasswords)
  } catch (error) {
    console.error('保存用户数据失败:', error)
    return false
  }
}

// 检查用户是否存在
export const userExists = (username) => {
  const users = getAllUsers()
  return users.some(user => user.username === username)
}

// 添加新用户
export const addUser = (username, password) => {
  try {
    // 检查用户是否已存在
    if (userExists(username)) {
      return { success: false, message: '用户名已存在' }
    }
    
    const users = getAllUsers()
    // 使用哈希密码
    users.push({ username, password: hashPassword(password) })
    
    const saved = saveUsers(users)
    if (saved) {
      return { success: true, message: '注册成功' }
    } else {
      return { success: false, message: '注册失败，请稍后重试' }
    }
  } catch (error) {
    console.error('添加用户失败:', error)
    return { success: false, message: '注册过程中发生错误，请稍后重试' }
  }
}

// 验证用户凭证
export const validateUser = (username, password) => {
  try {
    const users = getAllUsers()
    const user = users.find(u => u.username === username)
    
    if (!user) {
      return false
    }
    
    // 使用密码验证函数
    return verifyPassword(password, user.password)
  } catch (error) {
    console.error('验证用户凭证失败:', error)
    return false
  }
}

// 更新用户密码
export const updatePassword = (username, newPassword) => {
  try {
    const users = getAllUsers()
    const userIndex = users.findIndex(user => user.username === username)
    
    if (userIndex === -1) {
      return { success: false, message: '用户不存在' }
    }
    
    // 使用哈希密码
    users[userIndex].password = hashPassword(newPassword)
    const saved = saveUsers(users)
    
    if (saved) {
      return { success: true, message: '密码更新成功' }
    } else {
      return { success: false, message: '密码更新失败，请稍后重试' }
    }
  } catch (error) {
    console.error('更新用户密码失败:', error)
    return { success: false, message: '密码更新过程中发生错误，请稍后重试' }
  }
}

// 获取用户资料
export const getUserProfile = (username) => {
  const users = getAllUsers()
  const user = users.find(user => user.username === username)
  
  if (user) {
    return {
      username: user.username,
      email: user.email || '',
      avatar: user.avatar || '',
      bio: user.bio || ''
    }
  }
  
  return null
}

// 更新用户资料
export const updateUserProfile = (username, profileData) => {
  const users = getAllUsers()
  const userIndex = users.findIndex(user => user.username === username)
  
  if (userIndex === -1) {
    return { success: false, message: '用户不存在' }
  }
  
  // 更新用户资料
  users[userIndex] = {
    ...users[userIndex],
    ...profileData
  }
  
  const saved = saveUsers(users)
  
  if (saved) {
    return { success: true, message: '个人资料更新成功' }
  } else {
    return { success: false, message: '个人资料更新失败，请稍后重试' }
  }
}

// 获取用户统计数据
export const getUserStats = (username) => {
  try {
    const defaultStats = {
      totalGames: 0,
      reactionTests: 0,
      aimPractices: 0,
      bestReactionTime: 9999,
      highestScore: 0
    }
    
    return getItem(STORAGE_KEYS.USER_STATS(username), defaultStats)
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
    return {
      totalGames: 0,
      reactionTests: 0,
      aimPractices: 0,
      bestReactionTime: 9999,
      highestScore: 0
    }
  }
}

// 获取用户成就
export const getUserAchievements = (username) => {
  try {
    return getItem(STORAGE_KEYS.USER_ACHIEVEMENTS(username), [])
  } catch (error) {
    console.error('获取用户成就失败:', error)
    return []
  }
}

// 获取用户最近游戏记录
export const getRecentGames = (username) => {
  try {
    return getItem(STORAGE_KEYS.RECENT_GAMES(username), [])
  } catch (error) {
    console.error('获取用户最近游戏记录失败:', error)
    return []
  }
}

// 更新用户统计数据
export const updateUserStats = (username, gameType, score = null, reactionTime = null) => {
  try {
    const defaultStats = {
      totalGames: 0,
      reactionTests: 0,
      aimPractices: 0,
      bestReactionTime: 9999,
      highestScore: 0
    }
    
    let stats = getItem(STORAGE_KEYS.USER_STATS(username), defaultStats)
    
    // 保存更新前的统计数据，用于检查成就解锁条件
    const previousStats = { ...stats }
    
    // 更新游戏次数
    stats.totalGames++
    
    // 根据游戏类型更新相应统计
    if (gameType === 'reaction') {
      stats.reactionTests++
      if (reactionTime !== null && reactionTime < stats.bestReactionTime) {
        stats.bestReactionTime = reactionTime
      }
    } else if (gameType === 'aim') {
      stats.aimPractices++
      if (score !== null && score > stats.highestScore) {
        stats.highestScore = score
      }
    }
    
    // 保存更新后的统计数据
    setItem(STORAGE_KEYS.USER_STATS(username), stats)
    
    // 保存最近游戏记录
    saveRecentGame(username, gameType, score, reactionTime)
    
    // 检查并解锁成就
    checkAndUnlockAchievements(username, previousStats, stats, gameType, score, reactionTime)
    
    return true
  } catch (error) {
    console.error('更新用户统计数据失败:', error)
    return false
  }
}

// 保存最近游戏记录
const saveRecentGame = (username, gameType, score, reactionTime) => {
  try {
    let recentGames = getItem(STORAGE_KEYS.RECENT_GAMES(username), [])
    
    // 创建新的游戏记录
    const gameRecord = {
      id: Date.now(),
      type: gameType,
      score: score || 0,
      reactionTime: reactionTime,
      date: new Date().toISOString()
    }
    
    // 添加到记录列表开头
    recentGames.unshift(gameRecord)
    
    // 只保留最近10条记录
    if (recentGames.length > 10) {
      recentGames = recentGames.slice(0, 10)
    }
    
    // 保存更新后的记录
    setItem(STORAGE_KEYS.RECENT_GAMES(username), recentGames)
  } catch (error) {
    console.error('保存最近游戏记录失败:', error)
  }
}

// 检查并解锁成就
const checkAndUnlockAchievements = (username, previousStats, currentStats, gameType, score, reactionTime) => {
  try {
    let achievements = getItem(STORAGE_KEYS.USER_ACHIEVEMENTS(username), [])
    const unlockedAchievements = []
    
    // 检查首次游戏成就
    if (previousStats.totalGames === 0 && currentStats.totalGames === 1) {
      unlockAchievement(achievements, ACHIEVEMENT_TYPES.FIRST_GAME, unlockedAchievements)
    }
    
    // 检查游戏达人成就（累计10次游戏）
    if (previousStats.totalGames < 10 && currentStats.totalGames >= 10) {
      unlockAchievement(achievements, ACHIEVEMENT_TYPES.TEN_GAMES, unlockedAchievements)
    }
    
    // 检查反应大师成就（首次获得反应时间）
    if (gameType === 'reaction' && reactionTime && previousStats.bestReactionTime === 9999) {
      unlockAchievement(achievements, ACHIEVEMENT_TYPES.BEST_REACTION, unlockedAchievements)
    }
    
    // 检查得分王成就（首次获得高分）
    if (gameType === 'aim' && score && previousStats.highestScore === 0 && score > 0) {
      unlockAchievement(achievements, ACHIEVEMENT_TYPES.HIGH_SCORE, unlockedAchievements)
    }
    
    // 保存更新后的成就
    if (unlockedAchievements.length > 0) {
      setItem(STORAGE_KEYS.USER_ACHIEVEMENTS(username), achievements)
      
      // 可以在这里添加成就解锁通知逻辑
      console.log(`用户 ${username} 解锁了以下成就:`, unlockedAchievements)
    }
  } catch (error) {
    console.error('检查并解锁成就失败:', error)
  }
}

// 解锁单个成就
const unlockAchievement = (achievements, achievementType, unlockedAchievements) => {
  // 检查成就是否已解锁
  if (!achievements.some(a => a.type === achievementType)) {
    achievements.push({
      type: achievementType,
      unlockedAt: new Date().toISOString()
    })
    unlockedAchievements.push(achievementType)
  }
}

// 检查用户是否为VIP
export const isUserVIP = (username) => {
  const users = getAllUsers()
  const user = users.find(user => user.username === username)
  
  if (user && user.isVIP) {
    const expiryDate = new Date(user.vipExpiry)
    const now = new Date()
    
    // 检查VIP是否已过期
    if (expiryDate > now) {
      return {
        isVIP: true,
        expiry: expiryDate.toLocaleDateString()
      }
    } else {
      // VIP已过期，更新用户状态
      user.isVIP = false
      user.vipExpiry = null
      saveUsers(users)
    }
  }
  
  return { isVIP: false, expiry: null }
}

// 升级用户为VIP
export const upgradeToVIP = (username, days = 30) => {
  try {
    const users = getAllUsers()
    const userIndex = users.findIndex(user => user.username === username)
    
    if (userIndex === -1) {
      return { success: false, message: '用户不存在' }
    }
    
    // 检查用户是否已经是VIP
    if (users[userIndex].isVIP) {
      return { success: false, message: '您已经是VIP会员了' }
    }
    
    // 设置VIP状态，有效期指定天数
    users[userIndex].isVIP = true
    users[userIndex].vipExpiry = getVipExpiryDate(days)
    
    const saved = saveUsers(users)
    
    if (saved) {
      // 解锁VIP会员成就
      let achievements = getItem(STORAGE_KEYS.USER_ACHIEVEMENTS(username), [])
      const unlockedAchievements = []
      unlockAchievement(achievements, ACHIEVEMENT_TYPES.VIP_MEMBER, unlockedAchievements)
      
      if (unlockedAchievements.length > 0) {
        setItem(STORAGE_KEYS.USER_ACHIEVEMENTS(username), achievements)
      }
      
      return { success: true, message: '恭喜您已成功升级为VIP会员！' }
    } else {
      return { success: false, message: '升级失败，请稍后重试' }
    }
  } catch (error) {
    console.error('升级用户为VIP失败:', error)
    return { success: false, message: '升级过程中发生错误，请稍后重试' }
  }
}